<?php

require_once('functions.php');
require_once('init.php');
$member_id = $session->get("member_id");
$gametype = GAME2;

// Update top players.
$template->assign("players", get_top_players($gametype));
check_login($member_id);
check_no_questions($gametype, MAX_QUESTION_GAME2);
check_finish_game($member_id, $gametype);
$act = isset($_REQUEST['act']) ? $_REQUEST['act'] : -2;
$response = array();
$words = array();
switch (intval($act)) {
	case START:
		break;
	case END:
		//echo json_encode($_REQUEST);die;
		// Get array words from session. If not reponse session espired.
		$words = $session->get('words');
		if($words)
		{
			$correct = 0;
			foreach($words as $word)
			{
				$answer = $_REQUEST[$word['number']];
				//echo ucwords($word['word']) . " - " . ucwords($answer) . "\n";
				//var_dump(ucwords($word['word']) == ucwords($answer));
				if(strtoupper($word['word']) == strtoupper($answer))
				{
					$correct++;
				}
			}
			//die();
			// Insert game result.
			$query_insert_result = "INSERT INTO results(id, member_id, question_type_id, total, answered, passed, date_done)
									VALUES ('%s','%d','%d','%d','%d','%d',NOW())";
			$query_insert_result = sprintf($query_insert_result, 'NULL', $member_id, $gametype, MAX_QUESTION_GAME2, MAX_WORDS, $correct);
			$database->query($query_insert_result);
			$database->set_query("SELECT total, answered, passed FROM results WHERE member_id = $member_id");
			$result = $database->get_assoc();
			$response["result"] = $result;
			$session->set("member_score_game".$gametype, $result['passed']);
			$response["title"] = _LB_CONGRATULATIONS;
			$response["message"] = _MSG_CONGRATULATIONS_INFO;
			$response['players'] = get_top_players($gametype);
			echo json_encode($response);die();
		}
		//die();
		break;
}

$success = $pc->generate();
$limit_time = time() + WAITING_TIME;
while(!$success)
{
	$current_time = time();
	if($current_time > $limit_time)
	{
		$template->assign('message', "Server is busy, please try again later.");
		$template->display("nologin.tpl");
		die();
	}
	$success = $pc->generate();
	
}
$params = array(
	'colors' => "1",
	'fillflag' => 0,
	'cellflag' => '',
);
if (!$success) {
	die('Error please reload page.');
}
$html = $pc->getHTML($params); // Generate frame crossword
$words = $pc->getWords(); // Get number of words.
$session->set('words', $words);
//var_dump($words);die;
$cols = array();
$rows = array();
$arrDir = array();
foreach ($words as $key => $word) {
	if ($word['axis'] == 2) {
		$cols[$key + 1] = $word;
	} else {
		$rows[$key + 1] = $word;
	}
	$arrDir[$key + 1] = array(
		'axis'	=> $word['axis'], 
		'x'		=> $word['x']-1, 
		'y'		=> $word['y']-1);
}
$template->assign("crossword_frame", $html);
$template->assign("arrDir", json_encode($arrDir));
$template->assign("words", $words);
$template->assign("rows", $rows);
$template->assign("cols", $cols);
$template->display("culturalmosaic.tpl");
?>
